package com.gt.xmall.web;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gt.xmall.model.SysUser;
import com.gt.xmall.service.AccountService;


/**
 * 用户注册的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController {
	protected final transient Log log = LogFactory.getLog(getClass());
	@Autowired
	private AccountService accountService;

	@RequestMapping(method = RequestMethod.GET)
	public String registerForm() {
		return "register";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String register(@Valid SysUser user, RedirectAttributes redirectAttributes) {
		System.out.print("sysUser>>>>"+user.toString());
		log.info("sysUser>>>>"+user.toString());
		
		accountService.registerUser(user);
		redirectAttributes.addFlashAttribute("name", user.getName());
		return "redirect:/login";
	}

	/**
	 * Ajax请求校验loginName是否唯一。
	 */
	@RequestMapping(value = "checkName")
	@ResponseBody
	public String checkName(@RequestParam("name") String loginName) {
		if (accountService.findUserByName(loginName) == null) {
			return "true";
		} else {
			return "false";
		}
	}
}
